import { BrowserWindow, ipcMain } from 'electron'
import path from 'path'

import { initMenu } from './menu'
import { initNotices } from './notice'
import { initCookies } from './cookie'
import { initViews } from './browser-view'
import { useController } from './controller'
import { useStore } from './store'
import { calcWindowAreaSize } from '../util'

export function createWindow() {
  const win = new BrowserWindow({
    ...calcWindowAreaSize(),
    icon: path.join(__dirname, 'favicon.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  // Load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    // win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL)
    win.loadURL('http://test.dayukeji-inc.cn/browser')
  } else {
    win.loadURL('http://test.dayukeji-inc.cn/browser')
  }

  // Open the DevTools.
  if (process.env.NODE_ENV === 'development') {
    win.webContents.openDevTools()
  }

  onStartLogin(win)

  ipcMain.on('did-logout', () => {
    win.webContents.send('win-did-logout')
  })

  return win
}

function onStartLogin(win: BrowserWindow) {
  ipcMain.on('win-start-login', async (_event, code) => {
    const controller = useController()
    const store = useStore()
    try {
      const { userInfo, platforms, pages } = await controller.login({ code })
      store.setUserInfo(userInfo)
      store.setPlatforms(platforms)
      store.setPages(pages)
      // 初始化 cookie
      initCookies(win)
      // 初始化菜单
      initMenu(win)
      // 初始化 notice
      initNotices()
      // 初始化 view
      initViews(win)
      win.webContents.send('win-did-login', platforms)
    } catch (err) {
      console.error(err)
    }
  })
}
